﻿using System;
using System.Collections.Generic;
using System.Linq;
using Interfaces.FilterModels;
using Interfaces.Filters;
using Interfaces.Models;

namespace BusinessLogic.Models.Filter.GenericFilters
{
    public class XchangeRateFilter : BusinessLogic.Models.Filter.GenericFilters.PriceFilter<IXchangeRate, IXchangeRateFilterModel>, IXchangeRateFilter
    {
        public XchangeRateFilter(IXchangeRateFilterModel filterModel)
            : base(filterModel)
        {
            FilterModel = filterModel;
        }

        public override IEnumerable<object> Filtrate(IEnumerable<object> source)
        {
            var result = base.Filtrate(source);
            if (result != null)
            {
                var target = result as IEnumerable<IXchangeRate>;
                if (target == null)
                    throw new ArgumentException("Source has incorrect type.");
                return target.Where(GetRateFilter());
            }
            return null;
        }

        protected virtual Func<IXchangeRate, bool> GetRateFilter()
        {
            var lowRate = FilterModel.LowRate ?? float.MinValue;
            var highRate = FilterModel.HighRate ?? float.MaxValue;
            return item => item.Rate <= highRate && item.Rate >= lowRate;
        }

        public IXchangeRateFilterModel FilterModel { get;  set; }
    }
}
